package live.ifox.memo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import live.ifox.entity.Record;
import live.ifox.helper.CommonHelper;
import live.ifox.helper.DBHelper;

public class MainActivity extends AppCompatActivity {
    Spinner sp_categories;
    ListView listView;
    SwipeRefreshLayout swipeLayout;
    String selectCategory;
    List<String> categories;
    List<Record> items;
    DBHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = DBHelper.getInstance(this, "memo.db", 1);

        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);

        swipeLayout = findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });

        sp_categories = findViewById(R.id.sp_categories);
        sp_categories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectCategory = categories.get(position);
                updateView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        updateCategory();
    }

    void updateCategory() {
        categories = db.getCategories();
        if (categories.isEmpty()) {
            sp_categories.setAdapter(null);
            return;
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line);
        adapter.addAll(categories);
        sp_categories.setAdapter(adapter);
    }

    void updateView() {
        if (selectCategory == null || selectCategory.isEmpty())
            return;

        items = db.getItemsByCategory(selectCategory);
        if (items.isEmpty()) {
            listView.setAdapter(null);
            return;
        }

        List<Map<String, String>> model = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            Map<String, String> item = new HashMap<>();
            item.put("date_", items.get(i).getDate_());
            item.put("detail", items.get(i).getDetail());
            model.add(item);
        }
        if (model.size() > 0) {
            SimpleAdapter adapter = new SimpleAdapter(this, model,
                    android.R.layout.simple_list_item_2,
                    new String[]{"date_", "detail"},
                    new int[]{android.R.id.text1, android.R.id.text2});
            listView.setAdapter(adapter);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_ADD, 0, "添加...");
        menu.add(0, ID.ACTION_UPDATE_CATEGORY, 1, "更新类别");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ID.ACTION_ADD:
                Intent intent = new Intent(this, MemoEditor.class);
                intent.putExtra("categories", TextUtils.join(",", categories));
                startActivityForResult(intent, ID.ACTION_ADD);
                return true;
            case ID.ACTION_UPDATE_CATEGORY:
                updateCategory();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // getMenuInflater().inflate(R.menu.operate_menu, menu);
        menu.add(0, ID.ACTION_COPY, 0, "复制");
        menu.add(0, ID.ACTION_EDIT, 1, "编辑...");
        menu.add(0, ID.ACTION_REMOVE, 2, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (items.isEmpty())
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        Record record = items.get(position);
        switch (item.getItemId()) {
            case ID.ACTION_COPY:
                return do_copyItem(record);
            case ID.ACTION_EDIT:
                return do_editItem(record);
            case ID.ACTION_REMOVE:
                return do_removeItem(record);
            default:
                return super.onContextItemSelected(item);
        }
    }

    boolean do_copyItem(Record item) {
        String detail = item.getDetail();
        if (detail.isEmpty())
            return false;

        CommonHelper.setClipboardText(this, "Done", detail);
        CommonHelper.showMessage(this, "已复制到剪贴板");
        return true;
    }

    boolean do_editItem(Record item) {
        String uid = item.getUid();
        String category = item.getCategory();
        String detail = item.getDetail();
        if (uid.isEmpty() || category.isEmpty() || detail.isEmpty())
            return false;

        Intent intent = new Intent(this, MemoEditor.class);
        intent.putExtra("categories", TextUtils.join(",", categories));
        intent.putExtra("uid", uid);
        intent.putExtra("category", category);
        intent.putExtra("detail", detail);
        startActivityForResult(intent, ID.ACTION_EDIT);
        return true;
    }

    boolean do_removeItem(Record item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定操作").setMessage("确定删除吗？");
        builder.setPositiveButton(R.string.sure,
                (paramAnonymousDialogInterface, paramAnonymousInt) ->
                {
                    String uid = item.getUid();
                    if (uid.isEmpty())
                        return;

                    db.remove(uid);
                    updateView();
                });

        builder.setNegativeButton(R.string.cancel,
                (paramAnonymousDialogInterface, paramAnonymousInt) -> {
                });

        builder.create().show();
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != ID.RESULT_DONE || data == null)
            return;

        Record record = (Record) data.getSerializableExtra("record");
        switch (requestCode) {
            case ID.ACTION_EDIT:
                db.update(record);
                updateView();
                break;
            case ID.ACTION_ADD:
                db.addItem(record);
                selectCategory = record.getCategory();
                if (categories.isEmpty() || !categories.contains(selectCategory))
                    updateCategory();
                else
                    updateView();
                break;
        }
    }
}
